package org.dubnation.auth.service.impl;

import org.dubnation.auth.context.LoginContext;
import org.dubnation.auth.domain.EmployeeLogin;
import org.dubnation.auth.domain.RoleVO;
import org.dubnation.auth.domain.User;
import org.dubnation.auth.service.ILoginService;
import org.dubnation.org.domain.Employee;
import org.dubnation.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.UUID;

@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private EmployeeMapper mapper;

    @Autowired
    private EmployeeLogin employeeLogin;

    @Override
    public RoleVO login(User user) {
        //判断用户名或密码是否为空
        if (Objects.isNull(user.getUsername()) || Objects.isNull(user.getPassword())) throw new RuntimeException("没有输入用户名或密码");
        //若有用户名，根据用户查询员工信息
        Employee employee = mapper.queryByName(user);
        //判断密码是否正确
        if (!user.getPassword().equals(employee.getPassword())) throw new RuntimeException("密码错误");
        //若密码正确，用UUID生成随机数作为用户登录状态token，将token和员工信息存储到一个全局map中
        String token = UUID.randomUUID().toString().replace("-", "");
        employeeLogin.setId(employee.getId());
        employeeLogin.setUsername(employee.getUsername());
        employeeLogin.setEmail(employee.getEmail());
        employeeLogin.setHeadImage(employee.getHeadImage());
        LoginContext.messageMap.put(token,employeeLogin); //将登录状态信息存储到全局map中
        RoleVO roleVO = new RoleVO(token, employeeLogin);
        return roleVO;
    }
}
